from flask import Flask
from flask import request, send_file
import os

app = Flask(__name__)


@app.route("/")
def index():
    return "Hello World!"


@app.route("/fonts")
@app.route("/fonts/<name>")
def google_fonts(name=None):
    """
    google fonts
    """
    from itertools import product

    if name is not None:
        return send_file("fonts/" + name)

    suffix_table = {"ttf": "truetype"}
    weight_table = [
        "Thin",
        ["ExtraLight", "UltraLight"],
        "Light",
        ["", "Regular", "Normal"],
        "Medium",
        ["SemiBold", "DemiBold"],
        "Bold",
        ["ExtraBold", "UltraBold"],
        ["Black", "Heavy"],
    ]

    family, weight_style = request.args.get("family").split(":")

    weight_style = "400" if weight_style == "" else weight_style

    prefix = "fonts/" + family.replace(" ", "") + "-"

    buffer, status = "", True
    for weight_style in weight_style.split(","):
        style = weight_style[3:].title()
        weight_list = weight_table[int(weight_style[:1]) - 1]
        weight_list = [weight_list] if type(weight_list) == str else weight_list
        for weight, suffix in product(weight_list, suffix_table):
            file = "{}{}{}.{}".format(prefix, weight, style, suffix)
            if os.path.isfile(file):
                buffer += "@font-face {\n"
                buffer += "font-family: '{}';\n".format(family)
                buffer += "font-style: {};\n".format(weight_style[3:] if len(style) > 0 else "normal")
                buffer += "font-weight: {};\n".format(weight_style[:3])
                local_name1 = "{} {} {}".format(family, weight, style).replace("  ", " ").rstrip()
                local_name2 = "{}-{}{}".format(family, weight, style).replace(" ", "")
                buffer += "src: local('{}'), local('{}'), url('{}') format('{}');\n".format(
                    local_name1, local_name2, file, suffix_table[suffix]
                )
                buffer += "}\n"
                break
        else:
            status = False

    if status:
        status_code = 200
    elif buffer == "":
        status_code = 204
    else:
        status_code = 206

    return buffer, status_code, {"content-type": "text/css"}


if __name__ == "__main__":
    app.run()
